// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: hyuan

#include "coin2/exchange/phemex_futures/api_order/native_private_client.h"

#include <memory>
#include <sstream>

#include "coin2/exchange/base/api_util/url_params_builder.h"
#include "coin2/exchange/base/order/order.h"
#include "coin2/exchange/phemex_futures/symbology/product.h"

using coin2::exchange::phemex_futures::symbology::PhemexFuturesProduct;

#define CHECK_API_LIMIT(action_type)                                                      \
  auto ts = GetCurrentTimestamp();                                                        \
  if (!HasEnoughRateLimit(ts, action_type)) {                                             \
    LOG_EVERY_N(WARNING, 50) << "Hit rate limit or api temporary disabled, " << __func__; \
    api_block_info_[__func__]++;                                                          \
    return {};                                                                            \
  }                                                                                       \
  Push(1, ts, action_type);                                                               \
  api_req_info_[__func__]++;

namespace {
using ActionType = phemex::api_util::PhemexRateTracker::ActionType;
}

auto PhemexFuturesNativePrivateClient::GetRestOrderParams(
    const OrderSpec& order_spec,
    int64_t proc_order_id) -> RestParams {
  auto params = RestParams();

  PhemexFuturesProduct product =
      PhemexFuturesProduct::FromStr(order_spec.product, order_spec.order_created_time);
  auto product_holder = GetProductHolder(product, order_spec.order_created_time);
  params.set_symbol(order_spec.product);
  params.set_client_order_id(std::to_string(proc_order_id));
  if (order_spec.order_side == OrderSide::BUY_ORDER) {
    params.set_side("Buy");
  } else if (order_spec.order_side == OrderSide::SELL_ORDER) {
    params.set_side("Sell");
  } else {
    NOTREACHED() << "Unknown order side: " << static_cast<int>(order_spec.order_side);
  }
  auto formatter = product_holder->product_info().order_formatter();
  params.set_order_qty(formatter.FormatQty(order_spec.qty));
  if (order_spec.order_type != OrderType::MARKET_ORDER) {
    double price = order_spec.price;
    if (!is_linear) {
      price *= 1e4;
      params.set_price_ep(std::to_string(std::llround(price)));
    } else {
      params.set_price_ep(formatter.FormatPrice(price));
    }
  }
  if (order_spec.order_type == OrderType::MARKET_ORDER) {
    params.set_ord_type("Market");
  } else {
    params.set_ord_type("Limit");
    if (order_spec.post_only) {
      params.set_time_in_force("PostOnly");
    } else if (order_spec.duration == coin::proto::OrderDuration::FOK_ORDER) {
      params.set_time_in_force("FillOrKill");
    } else if (order_spec.duration == coin::proto::OrderDuration::IOC_ORDER) {
      params.set_time_in_force("ImmediateOrCancel");
    } else {
      params.set_time_in_force("GoodTillCancel");
    }
  }

  return params;
}

auto PhemexFuturesNativePrivateClient::GetRestCancelParams(const IOrderContext& order_context)
    -> RestParams {
  auto params = RestParams();
  const std::string& product_str = order_context.order_spec().product;
  params.set_symbol(product_str);
  if (order_context.has_exchange_order_id()) {
    params.set_order_id(order_context.exchange_order_id());
  } else {
    params.set_client_order_id(std::to_string(order_context.proc_order_id()));
  }

  return params;
}

PhemexFuturesNativePrivateClient::PhemexFuturesNativePrivateClient(
    const MarketExchangeApi& mea,
    const NativeClientConfig& config_override) {
  mea_ = mea;
  is_linear = mea.api == "v1-linear";
  NativeClientConfig config;
  config.set_rest_host("api.phemex.com");
  config.set_rest_host_port(443);
  config.MergeFrom(config_override);
  LOG(INFO) << "[PhemexFuturesNativePrivateClient] config: " << config.DebugString();

  auths_.Construct<PhemexRestAuth, NativeClientConfig>(config);

  rate_tracker_ = std::make_unique<PhemexRateTracker>(mea_, config);
  local_rate_tracker_ = static_cast<PhemexRateTracker*>(rate_tracker_.get());
  start_time_ = GetCurrentTimestamp();
}

std::shared_ptr<AsioHttpContext> PhemexFuturesNativePrivateClient::QueryAccountInfo(
    const RestParams& params) {
  CHECK_API_LIMIT(ActionType::QUERY);

  std::string path = "/accounts/accountPositions";
  if (is_linear) {
    path = "/g-accounts/accountPositions";
  }

  UrlParamsBuilder builder;
  builder.PutGet("currency", params.currency());
  auto context =
      std::shared_ptr<AsioHttpContext>(GetAuth()->CreateRequestByGetWithSignature(path, &builder));

  context->query_type = OrderSubTopicId::REST_ACCOUNTS;
  context->extra_info = DebugString();
  return context;
}

std::shared_ptr<AsioHttpContext> PhemexFuturesNativePrivateClient::QueryOpenOrders(
    const RestParams& params) {
  CHECK_API_LIMIT(ActionType::QUERY);

  std::string path = "/orders/activeList";
  if (is_linear) {
    path = "/g-orders/activeList";
  }

  UrlParamsBuilder builder;
  builder.PutGet("symbol", params.symbol());
  auto context =
      std::shared_ptr<AsioHttpContext>(GetAuth()->CreateRequestByGetWithSignature(path, &builder));

  context->query_type = OrderSubTopicId::REST_OPEN_ORDERS;
  context->extra_info = DebugString();
  return context;
}

std::shared_ptr<AsioHttpContext> PhemexFuturesNativePrivateClient::QueryHistoryOrders(
    const RestParams& params) {
  CHECK_API_LIMIT(ActionType::UNKNOWN);

  UrlParamsBuilder builder;
  std::string path;
  if (is_linear) {
    path = "/api-data/g-futures/orders";
    builder.PutGet("limit", 200);
  } else {
    path = "/exchange/order/list";
  }
  builder.PutGet("symbol", params.symbol());

  auto context =
      std::shared_ptr<AsioHttpContext>(GetAuth()->CreateRequestByGetWithSignature(path, &builder));

  context->query_type = OrderSubTopicId::REST_DONE_ORDERS;
  context->extra_info = DebugString();
  return context;
}

std::shared_ptr<AsioHttpContext> PhemexFuturesNativePrivateClient::QueryFills(
    const RestParams& params) {
  CHECK_API_LIMIT(ActionType::UNKNOWN);

  UrlParamsBuilder builder;
  std::string path;
  if (is_linear) {
    path = "/api-data/g-futures/trades";
    builder.PutGet("limit", 200);
  } else {
    path = "/exchange/order/trade";
  }
  builder.PutGet("symbol", params.symbol());

  auto context =
      std::shared_ptr<AsioHttpContext>(GetAuth()->CreateRequestByGetWithSignature(path, &builder));

  context->query_type = OrderSubTopicId::REST_FILL_ORDERS;
  context->extra_info = DebugString();
  return context;
}

std::shared_ptr<AsioHttpContext> PhemexFuturesNativePrivateClient::QueryTransfer(
    const RestParams& params) {
  CHECK_API_LIMIT(ActionType::UNKNOWN);

  UrlParamsBuilder builder;
  builder.PutGet("currency", params.currency());
  auto context = std::shared_ptr<AsioHttpContext>(
      GetAuth()->CreateRequestByGetWithSignature("/exchange/margins/transfer", &builder));

  context->query_type = OrderSubTopicId::TRANSFER;
  context->extra_info = DebugString();
  return context;
}

void PhemexFuturesNativePrivateClient::Prepare() {
  using coin2::exchange::phemex::api_util::PhemexRateTracker;
  auto* tracker = dynamic_cast<PhemexRateTracker*>(this->rate_tracker_.get());
  mb_->Subscribe("phemex/rate_limit_contract", [tracker](const std::string&, void* data) {
    int64_t rate_limit_remain = reinterpret_cast<int64_t>(data);
    tracker->UpdateRateLimitContract(rate_limit_remain);
  });

  mb_->Subscribe("phemex/enable_time_contract", [this](const std::string&, void* data) {
    int64_t value = reinterpret_cast<int64_t>(data);
    local_rate_tracker_->UpdateContractEnableTime(value);
    LOG(WARNING) << "Phemex native client enable_time for contract: " << value;
  });

  mb_->Subscribe("phemex/rate_limit_others", [tracker](const std::string&, void* data) {
    int64_t rate_limit_remain = reinterpret_cast<int64_t>(data);
    tracker->UpdateRateLimitOthers(rate_limit_remain);
  });

  mb_->Subscribe("phemex/enable_time_others", [this](const std::string&, void* data) {
    int64_t value = reinterpret_cast<int64_t>(data);
    local_rate_tracker_->UpdateOthersEnableTime(value);
    LOG(WARNING) << "Phemex native client enable_time for others: " << value;
  });
}

std::string PhemexFuturesNativePrivateClient::DebugString() const {
  double delta_t = (GetCurrentTimestamp() - start_time_) / 1.0e9;
  std::stringstream ss;
  ss << "PhemexFuturesNativePrivateClient::DebugString\n";
  ss << "api info\n";
  for (auto& [name, value] : api_req_info_) {
    int32_t blocked = 0;
    if (api_block_info_.count(name) > 0) {
      blocked = api_block_info_.at(name);
    }
    int32_t total_req = value + blocked;
    ss << name << " (total:" << total_req << ", succeeded: " << value << ", blocked: " << blocked
       << ", req_rate: " << value / delta_t << ", block_rate: " << blocked / delta_t << ")\n";
  }
  return ss.str();
}

std::shared_ptr<AsioHttpContext> PhemexFuturesNativePrivateClient::PlaceOrder(
    const RestParams& params) {
  CHECK_API_LIMIT(ActionType::PLACE);

  UrlParamsBuilder builder;
  std::string path;
  if (is_linear) {
    path = "/g-orders";
    builder.PutPost("orderQtyRq", params.order_qty());
    builder.PutPost("priceRp", params.price_ep());
    builder.PutPost("posSide", "Merged");
  } else {
    path = "/orders";
    builder.PutPost("orderQty", params.order_qty());
    builder.PutPost("priceEp", params.price_ep());
  }
  builder.PutPost("symbol", params.symbol());
  builder.PutPost("clOrdID", params.client_order_id());
  builder.PutPost("side", params.side());
  builder.PutPost("ordType", params.ord_type());
  builder.PutPost("timeInForce", params.time_in_force());
  auto context =
      std::shared_ptr<AsioHttpContext>(GetAuth()->CreateRequestByPostWithSignature(path, &builder));

  context->query_type = OrderSubTopicId::SUBMIT_RESPONSE;
  context->extra_info = DebugString();
  return context;
}

std::shared_ptr<AsioHttpContext> PhemexFuturesNativePrivateClient::CancelOrder(
    const RestParams& params) {
  CHECK_API_LIMIT(ActionType::CANCEL);

  std::string path;
  UrlParamsBuilder builder;
  if (is_linear) {
    path = "/g-orders/cancel";
    builder.PutGet("posSide", "Merged");
  } else {
    path = "/orders/cancel";
  }
  builder.PutGet("symbol", params.symbol());
  if (params.has_order_id()) {
    builder.PutGet("orderID", params.order_id());
  } else if (params.has_client_order_id()) {
    builder.PutGet("clOrdID", params.client_order_id());
  }
  auto context = std::shared_ptr<AsioHttpContext>(
      GetAuth()->CreateRequestByDeleteWithSignature(path, &builder));

  context->query_type = OrderSubTopicId::CANCEL_RESPONSE;
  context->extra_info = DebugString();
  return context;
}

std::shared_ptr<AsioHttpContext> PhemexFuturesNativePrivateClient::PlaceOrderNorm(
    const OrderExecution& order_exe) {
  const auto& order_spec = *order_exe.order_spec;
  const auto proc_order_id = order_exe.proc_order_id;
  auto params = GetRestOrderParams(order_spec, proc_order_id);
  return PlaceOrder(params);
}

std::shared_ptr<AsioHttpContext> PhemexFuturesNativePrivateClient::CancelOrderNorm(
    const OrderExecution& order_exe) {
  auto params = GetRestCancelParams(*order_exe.oc);
  return CancelOrder(params);
}
